using System;
using System.Linq;
using System.Linq.Expressions;
using SharePoint.Orm.Helpers;

namespace SharePoint.Orm {
	public class SPQueryProvider : IQueryProvider {
		private readonly SPDataContext _dataContext;

		public SPQueryProvider(SPDataContext dataContext) {
			_dataContext = dataContext;
		}

		public IQueryable CreateQuery(Expression expression) {
			Type elementType = TypeSystem.GetElementType(expression.Type);
			try {
				return (IQueryable)Activator.CreateInstance(typeof(SPQueryable<>).MakeGenericType(elementType), new object[] { _dataContext, this, expression });
			} catch (System.Reflection.TargetInvocationException tie) {
				throw tie.InnerException;
			}
		}

		public IQueryable<TResult> CreateQuery<TResult>(Expression expression) {
			return new SPQueryable<TResult>(_dataContext, this, expression);
		}

		public object Execute(Expression expression) {
			return SPQueryContext.Execute(_dataContext, expression, false);
		}

		public TResult Execute<TResult>(Expression expression) {
			bool IsEnumerable = (typeof(TResult).Name == "IEnumerable`1");
			return (TResult)SPQueryContext.Execute(_dataContext, expression, IsEnumerable);
		}
	}
}